const { queryDBPromise } = require('../db/db')
const express = require('express')
const goodsRouter = express.Router() // 路由对象

/**
 * 添加商品
 *    => 保存商品到数据库商品表
 *  method: post
 *  url: /goods
 *  参数: name, price, num
 */
goodsRouter.post('/goods', (req, res) => {
	// 1. 接收参数
	const name = req.body.name // 商品名称
	const price = req.body.price // 商品价格
	const num = req.body.num //数量

	// 2. 保存到商品表
	const sql = `INSERT INTO goods (name,price,num)VALUES('${name}',${price},${num})`
	queryDBPromise(sql).then(data => {
		// 3. 响应数据
		res.send({
			code: 1,
			message: '添加商品成功',
		})
	})
})

/**
 * 查看商品列表
 */
goodsRouter.get('/goods', (req, res) => {
	const sql = `SELECT id,name,price,num,url,category_id,description FROM goods`
	queryDBPromise(sql).then(data => {
		console.log('data ', data)
		res.send({
			code: 1,
			list: data,
		})
	})
})

/**
 * 查看商品
 * 根据id查找商品
 *   method:GET
 *    url: '/goods/1'
 */
goodsRouter.get('/goods/:id', (req, res) => {
	const id = req.params.id //商品id

	const sql = `SELECT id,name,price,num,url,category_id,description FROM goods WHERE id = ${id}`
	queryDBPromise(sql)
		.then(data => {
			res.send({
				code: 1,
				goods: data[0],
			})
		})
		.catch(err => {
			res.send({
				code: -1,
				message: '查询商品出错!',
			})
		})
})

/**
 * 修改商品
 *  根据商品id更新商品价格
 *    method: put
 *    url: /goods/1
 *    参数： body
 *            price:88.98
 */
goodsRouter.put('/goods/:id', (req, res) => {
	const id = req.params.id //商品id
	const price = req.body.price //商品价格

	const sql = `UPDATE goods SET price = ${price} WHERE id = ${id}`
	queryDBPromise(sql)
		.then(data => {
			res.send({
				code: 1,
				message: '修改商品成功!',
			})
		})
		.catch(err => {
			res.send({
				code: -1,
				message: '修改商品失败！',
			})
		})
})

/**
 * 删除商品
 * 根据商品id删除商品
 *   method: Delete
 *   url: /goods/1
 */
goodsRouter.delete('/goods/:id', (req, res) => {
	const id = req.params.id //商品id

	const sql = `DELETE FROM goods WHERE id = ${id}`
	queryDBPromise(sql)
		.then(data => {
			res.send({
				code: 1,
				message: '删除商品成功!',
			})
		})
		.catch(err => {
			res.send({
				code: -1,
				message: '删除商品失败！',
			})
		})
})

module.exports = {
	goodsRouter,
}
